package cn.zc.gateway.filter;

import cn.tools.common.adapter.IgnoreTokenConfig;

import cn.tools.common.enums.AuthEnum;
import cn.tools.core.base.R;
import cn.tools.core.exception.BizException;
import cn.zc.gateway.service.AnalysisTokenServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;


/**
 * @author: e
 * @date: 2021/12/16
 * @description: 网关初始拦截器
 */
//order表示这是第几个拦截器，值越小，优先级越高
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Resource
    private AnalysisTokenServiceImpl analysisTokenServiceImp;

    @Override
    public int getOrder(){
        return -1;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求参数,我们这里有提到这里是响应式编程，所以取值区别有点大，获取的request也不是httpServeletRequest


        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //通过getQueryParams()方法获取出所有参数，这里返回是一个类似map的类
        MultiValueMap<String, String> queryParams = request.getQueryParams();


        //2.判断一下，路径是否要进行放行,调用tools-common下的静态类进行判断路径是否无需拦截
        if(IgnoreTokenConfig.isIgnore(IgnoreTokenConfig.LIST,request.getPath().toString())){
            return chain.filter(exchange);
        }


        //2.获取参数中的token,调用getFirst方法可以精确匹配到对应参数,所有值都是按string格式返回
        //String token = queryParams.getFirst("token");
        List<String> heads = request.getHeaders().get(AuthEnum.TOKEN.getValue());


        if(heads == null){
            return gateWayException(response);
        }

        String token = heads.get(0);

        //调用方法解析token,将解析后的token中的Body值存放至头部中，放入请求继续往下传
        ServerHttpRequest serverHttpRequestHead = analysisTokenServiceImp.decodeHS256(request, token);

        ServerWebExchange build = exchange.mutate().request(serverHttpRequestHead).build();
        return chain.filter(build);
    }


    public Mono<Void> gateWayException(ServerHttpResponse response){
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            ObjectMapper mapper = new ObjectMapper();
            response.setStatusCode(HttpStatus.BAD_GATEWAY);
        try {
            return dataBufferFactory.wrap(mapper.writeValueAsBytes(R.fail("未携带参数")));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return  dataBufferFactory.wrap(new byte[0]);
        }
        }));
    }



}
